package com.atguigu.flink.chapter11;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/9/24 10:10
 */
public class Flink02_Table_BaseUse_Agg {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
    
        DataStreamSource<WaterSensor> waterSensorStream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 2000L, 20),
//                             new WaterSensor("sensor_2", 3000L, 30),
                             new WaterSensor("sensor_1", 4000L, 40),
//                             new WaterSensor("sensor_2", 6000L, 60)
                             new WaterSensor("sensor_1", 5000L, 50)
            );
        
        // 1. 表的执行环境
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        // 2. 把流转成表(动态表)
        Table table = tenv.fromDataStream(waterSensorStream);
        
        // select  sum(vc) vc_sum from t group by id;
        Table result = table
            .groupBy($("id"))
            .aggregate($("vc").sum().as("vc_sum"))
            .select($("id"), $("vc_sum"));
    
//        DataStream<Tuple2<Boolean, Row>> stream = tenv.toRetractStream(result, Row.class);
//        stream.print();
        result.execute().print(); // 测试用, 直接打印表的结果
    
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
